﻿#include "ConnectToHostResponsePrivate.h"
#include "qftp.h"
#include "ConnectToHostResponse.h"

BEGIN_NAMESPACE_ZFTPNS

ConnectToHostResponsePrivate::ConnectToHostResponsePrivate(QObject *parent) :
    ZFtpResponsePrivate(parent),
    q_ptr(NULL)
{

}

void ConnectToHostResponsePrivate::listenTo(QSharedPointer<QFtp> ftp,
                                            QSharedPointer<ZFtpConfig> ftp_config)
{
    // 保证继承的信号工作
    ZFtpResponsePrivate::listenTo(ftp, ftp_config);

    if (!ftp) return;
    ftp->disconnect(this, SLOT(slotCommandFinished(int,bool)));
    ftp->disconnect(this, SLOT(slotFtpStateChanged(int)));
    connect(ftp.data(), SIGNAL(commandFinished(int,bool)), SLOT(slotCommandFinished(int,bool)));
    connect(ftp.data(), SIGNAL(stateChanged(int)), SLOT(slotFtpStateChanged(int)));
}

void ConnectToHostResponsePrivate::setPublicResponseObject(
        QPointer<ZFtpResponse> response)
{
    ZFtpResponsePrivate::setPublicResponseObject(response);
    q_ptr = qobject_cast<ConnectToHostResponse *>(response.data());
    Q_ASSERT(q_ptr);
}

QPointer<ZFtpResponse> ConnectToHostResponsePrivate::publicObject()
{
    return QPointer<ZFtpResponse>(q_ptr);
}

void ConnectToHostResponsePrivate::setFtpTaskID(const int &id)
{
    ZFtpResponsePrivate::setFtpTaskID(id);

    // 解决连接中再次连接崩溃或不响应的问题：
    // 增加检测：外部设置了无效的任务id，则认为任务失败
    if (!isFtpTaskIDValid())
    {
        // 异步非阻塞消息
        QMetaObject::invokeMethod(q_ptr, "sigResult", Qt::QueuedConnection, Q_ARG(bool, false));
    }
}

void ConnectToHostResponsePrivate::slotCommandFinished(int id, bool error)
{
    if (this->ftpTaskID() != id) return;

    // ftp任务id置为无效
    invalidFtpTaskID();

    Q_ASSERT(q_ptr);
#if 0
    emit q_ptr->sigResult(!error);
#else
    // 异步非阻塞消息
    QMetaObject::invokeMethod(q_ptr, "sigResult", Qt::QueuedConnection, Q_ARG(bool, !error));
#endif
}

void ConnectToHostResponsePrivate::slotFtpStateChanged(int state)
{
}

END_NAMESPACE
